/*
 *  Copyright 2011 derek.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package com.aocore.packet.GC;

import com.aocore.d2data.GameMessageType;
import com.aocore.packet.GCPacket;
import com.aocore.util.ByteConverter;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

/**
 *
 * @author derek
 */
public class SendMessage extends GCPacket
{
    protected GameMessageType type;
    protected String message;
    protected String recipient;

    public SendMessage(byte... data)
    {
        super(data);

        ByteBuffer byteBuffer = ByteBuffer.wrap(data);
        byteBuffer.order(ByteOrder.LITTLE_ENDIAN); 
        this.type = GameMessageType.valueOf(byteBuffer.getShort(1));
        this.message = ByteConverter.getString(data, 3);
        if (this.type == GameMessageType.GameWhisper)
            this.recipient = ByteConverter.getString(data, 4 + this.message.length());
    }

    public SendMessage(GameMessageType type, String message)
    {
        this(type, message, null);
    }

    public SendMessage(GameMessageType type, String message, String recipient)
    {
        if (message == null || message.length() == 0)
            throw new IllegalArgumentException();
        int r = recipient != null ? recipient.length() : 0;
        data = new byte[6 + message.length() + r];
        data[0] = 0x15;
        data[1] = (byte)(type.getId());
        data[2] = (byte)(type.getId() >>> 8);
        for (int i = 0; i < message.length(); i++)
            data[3 + i] = (byte)message.getBytes()[i];
        if (r > 0)
        {
            r = 4 + message.length();
            for (int i = 0; i < recipient.length(); i++)
                data[r + i] = (byte)recipient.getBytes()[i];
        }
    }

    public GameMessageType getType()
    {
        return type;
    }

    public String getMessage()
    {
        return message;
    }

    public String getRecipient()
    {
        return recipient;
    }

    @Override
    public String toString()
    {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("GCPacket: ").append("SendMessage").append("\n");
        stringBuilder.append("type: ").append(type).append("\n");
        stringBuilder.append("message: ").append(message).append("\n");
        stringBuilder.append("recipient: ").append(recipient).append("\n");
        return stringBuilder.toString();
    }
}
